<script setup>
  import { reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox  } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { ModifyUserInfo, ModifyPassword, UserInvitationCode } from '@/api/user'
  import { UploadImage } from '@/api/media/image'
  import useAppStatusStore from '@/stores/appStatus'
  import useUserInfoStore from '@/stores/userinfo'
  const userInfoStore = useUserInfoStore()  // 用户信息store
  const appStatusStore = useAppStatusStore()
  const appRouter = useRouter()

  // 用户信息
  const baseInfoList = reactive([
    {
      label: '<span>用</span><span>户</span><span>昵</span><span>称</span>',
      content: '',
      newContent: '',
      isEdit: false,
      fixed: false,
      key: 'nickname',
    },
    {
      label: '<span>用</span><span>户</span><span>ID</span>',
      content: '',
      newContent: '',
      isEdit: false,
      fixed: true,
      key: 'ssn',
    },
    {
      label: '<span>姓</span><span>名</span>',
      content: '',
      newContent: '',
      isEdit: false,
      fixed: true,
      key: 'username',
    },
    {
      label: '<span>单</span><span>位</span>',
      content: '',
      newContent: '',
      isEdit: false,
      fixed: false,
      key: 'company',
    },
    {
      label: '<span>担</span><span>任</span><span>职</span><span>位</span>',
      content: '',
      newContent: '',
      isEdit: false,
      fixed: false,
      key: 'job'
    }
  ])

  // 密码修改
  const passwordObj = reactive({
    old: '',
    showOld: false,
    new1: '',
    showNew1: false,
    new2: '',
    showNew2: false,
    saveLoading: false,
  })
  // 头像修改
  const avatarObj = reactive({
    showDialog: false,
    newUrl: userInfoStore.avatarUrl,
    uploading: false,
    buttonText: '确定保存'
  })

  // 邀请码
  const invitationData = reactive({
    code: '',
    hasCode: false,
    getLoading: false
  })

  const toGetInvitationCode = () => {
    invitationData.getLoading = true
    UserInvitationCode().then((res) => {
      invitationData.code = res.data.invitation_code
      invitationData.hasCode = res.data.invitation_code ? true : false
      invitationData.getLoading = false
    })
  }

  const toSaveNewPassword = () => {
    if (passwordObj.old.length < 1) {
      ElMessage.error('请填写旧密码!')
      return
    }
    if (passwordObj.new1 !== passwordObj.new2) {
      ElMessage.error('两次密码输入不一致!')
      return
    }
    if (
        passwordObj.old.length < 6 || 
        passwordObj.old.length > 20 || 
        passwordObj.new1.length < 6 || 
        passwordObj.new1.length > 20
      ) {
      ElMessage.error('请输入6-20位的密码!')
      return
    }
    const psdData = {
      password: passwordObj.old,
      new_password1: passwordObj.new1,
      new_password2: passwordObj.new2
    }
    passwordObj.saveLoading = true
    ModifyPassword(psdData).then((res) => {
      passwordObj.saveLoading = false
      ElMessageBox.confirm(
        res.message,
        '提示',
        {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'success',
          showClose: false,
        }
      ).then(() => {
        userInfoStore.appUserLogout()
        appRouter.replace({path: '/'})
      })
    }).catch(() => {
      passwordObj.saveLoading = false
    })
  }
  
  const toSignin = () => {
    appStatusStore.showSignin = true
  }

  const toSaveInfo = (item) => {
    let newData = {}
    newData[item.key] = item.newContent
    if (item.newContent === item.content) {
      item.isEdit = false
      return
    }
    ModifyUserInfo(newData).then((res) => {
      ElMessage.success({
        message: res.message
      })
      item.content = item.newContent
      item.isEdit = false
      if (item.key === 'nickname') {
        userInfoStore.nickname = item.newContent
      }
    })
  }

  const avatarChange = (rawFile) => {
    if (['image/jpeg', 'image/png'].indexOf(rawFile.raw.type) < 0) {
      ElMessage.error('头像文件仅支持JPG/PNG格式!')
      return
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('头像文件不能大于2MB!')
      return
    }
    // 向后端上传文件
    const formData = new FormData()
    formData.append('scope', 'avatar')
    formData.append('image', rawFile.raw)
    avatarObj.buttonText = '设置中'
    avatarObj.uploading = true
    UploadImage(formData).then((res) => {
      avatarObj.newUrl = res.data.image_url
      avatarObj.buttonText = '确定保存'
      avatarObj.uploading = false
    }).catch(() => {
      ElMessage.error('图片保存失败了...')
      avatarObj.buttonText = '确定保存'
      avatarObj.uploading = false
    })
  }

  const toSaveAvatar = () => {
    if (avatarObj.newUrl === userInfoStore.avatarUrl) {
      return
    }
    if (avatarObj.newUrl.length < 1) {
      return
    }
    avatarObj.buttonText = '保存中'
    avatarObj.uploading = true
    ModifyUserInfo({avatar: avatarObj.newUrl}).then((res) => {
      userInfoStore.avatarUrl =res.data.avatar_url
      avatarObj.buttonText = '确定保存'
      avatarObj.uploading = false
      setTimeout(() => {
        avatarObj.showDialog = false
      }, 500)
    }).catch(() => {
      avatarObj.buttonText = '确定保存'
      avatarObj.uploading = false
    })
  }
  
  onMounted(() => {
    // 获取用户的信息
    userInfoStore.getAppUserInfo().then((res) => {
      const resData = res.data
      invitationData.code = resData.invitation_code
      invitationData.hasCode = resData.invitation_code ? true : false
      baseInfoList.map((item) => {
        item.content = resData[item.key]
        item.newContent = resData[item.key]
        if (!resData[item.key]) {
          item.content='未填写'
        }
      })
    })
  }) 
</script>
<template>
  <div class="page-container">
    <div class="content">
      <el-tabs class="tabs-box" tab-position="left" type='border-card' :stretch="true">
        <el-tab-pane label="个人资料">
          <div class="base_info">
            <div class="avatar-info">
              <!-- 头像和VIP信息 -->
              <div class="avatar" @click="avatarObj.showDialog = true">
                <el-avatar :class="userInfoStore.isVip ? 'vip-avatar':''" :size="80" :src="userInfoStore.avatarUrl" />
              </div>
              <div class="activation">
                <div :class="userInfoStore.isVip ? 'vip-nickname':'nickname'">{{ userInfoStore.nickname }}</div>
                <div class="vip-activation">
                  <el-icon :size="18"><svg-icon :name="userInfoStore.isVip ? 'vip': 'vip-ex'"></svg-icon></el-icon>
                  <div class="active-num">{{ userInfoStore.activation }}</div>
                </div>
                <div class="active-tip">活跃度根据您的【登录】情况和【<span class="signin" @click="toSignin">签到</span>】而增加.</div>
              </div>
            </div>
            <div class="invitation">
              <div>
                我的邀请码：
              </div>
              <div v-if="invitationData.hasCode" class="code-num">
                {{ invitationData.code }}
              </div>
              <div v-else>
                <el-button
                  type="primary"
                  plain
                  :loading="invitationData.getLoading"
                  @click="toGetInvitationCode"
                >
                  获取邀请码
                </el-button>
              </div>
            </div>
          </div>
          
          <div class="info-list">
            <div class="info-label">基本信息</div>
            <div>
              <div v-for="(item, index) in baseInfoList" :key="index" class="info-row">
                <div class="row-label" v-html="item.label"></div>
                <div v-if="item.isEdit" class="edit-box">
                  <el-input v-model="item.newContent"></el-input>
                  <el-button
                    link
                    type="primary"
                    icon="Check"
                    @click="toSaveInfo(item)"
                  >保存</el-button>
                  <el-button
                    link
                    icon="Close"
                    @click="item.isEdit = false"
                  >取消</el-button>
                </div>
                <div v-else class="content-box">
                  <div class="row-text">{{ item.content }}</div>
                  <div class="row-action">
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="item.isEdit = true"
                    v-if="!item.fixed"
                  >
                    编辑
                  </el-button>
                </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="账号设置">
          <div class="info-list">
            <div class="info-label">密码修改</div>
            <div class="password-form">
              <el-form label-width="80px">
                <el-form-item label="输入旧密码">
                  <el-input
                    v-model="passwordObj.old"
                    placeholder="请输入旧密码"
                    :type="passwordObj.showOld ? 'text': 'password'"
                  >
                    <template #suffix>
                      <el-icon @click="passwordObj.showOld = !passwordObj.showOld">
                        <View v-if="passwordObj.showOld" /> 
                        <Hide v-else />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="输入新密码">
                  <el-input
                    v-model="passwordObj.new1" 
                    placeholder="请输入新密码"
                    :type="passwordObj.showNew1 ? 'text': 'password'"
                  >
                    <template #suffix>
                      <el-icon @click="passwordObj.showNew1 = !passwordObj.showNew1">
                        <View v-if="passwordObj.showNew1" /> 
                        <Hide v-else />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="确认新密码">
                  <el-input
                    v-model="passwordObj.new2"
                    placeholder="请再次输入新密码"
                    :type="passwordObj.showNew2 ? 'text': 'password'"
                  >
                    <template #suffix>
                      <el-icon @click="passwordObj.showNew2 = !passwordObj.showNew2">
                        <View v-if="passwordObj.showNew2" /> 
                        <Hide v-else />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
              <div class="modify-password-aciton">
                <el-button
                  class="confirm-btn"
                  type="primary"
                  :loading="passwordObj.saveLoading"
                  @click="toSaveNewPassword"
                >确认修改</el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 弹窗更换头像 -->
    <el-dialog
      v-model="avatarObj.showDialog"
      title="更换头像"
      width="700px"
    >
      <div class="avatar-dialog">
        <div class="old">
          <el-avatar :size="170" :src="avatarObj.newUrl" />
        </div>
        <div class="blank-box"></div>
        <div class="new">
          <el-upload
            action=""
            class="avatar-uploader"
            accept="image/png, image/jpeg"
            :show-file-list="false"
            :auto-upload="false"
            :before-upload="() => false"
            :on-change="avatarChange"
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                使用小于 2M 的 JPG/PNG 图片文件.
              </div>
            </template>
          </el-upload>
        </div>
      </div>
      <template #footer>
        <div class="footer">
          <el-button
            class="action-btn"
            size="default"
            @click="avatarObj.showDialog = false"
          >取消</el-button>
          <el-button
            type="primary"
            class="action-btn"
            size="default"
            :loading="avatarObj.uploading"
            @click="toSaveAvatar"
          >
            {{ avatarObj.buttonText }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
  .page-container {
    width: 1400px;
    height: 900px;
    .content {
      .tabs-box {
        height: 885px;
        margin: 10px 0;
        ::v-deep(.el-tabs__item) {
          width: 200px;
          justify-content: center;
        }
        .base_info {
          margin: 0 50px;
          padding: 50px;
          box-shadow: 0 0 2px #efefef;
          background-color: #f5f7fa;
        .avatar-info {
          display: flex;
          align-items: center;
          .avatar {
            cursor: pointer;
          }
          .vip-avatar {
            border: 2px solid #ffa500;
          }
          .activation {
            margin-left: 20px;
            line-height: 28px;
            .nickname {
              font-size: 18px;
              font-weight: 600;
            }
            .vip-nickname {
              font-size: 18px;
              font-weight: 700;
              color: $goldenColor;
            }
            .vip-activation {
              display: flex;
              align-items: center;
              .active-num {
                font-size: 13px;
                margin-left: 6px;
              }
            }
            .active-tip {
              font-size: 13px;
              color: #6a6a6a;
              .signin{
                color: #48a2ff;
                font-weight: 600;
                cursor: pointer;
              }
            }
          }
          
        }
        .invitation {
          display: flex;
          align-items: center;
          margin-top: 20px;
          font-size: 15px;
        }
        .code-num {
          font-size: 15px;
          font-weight: 600;
          color: #d70000;
        }
      }
        .info-list {
          margin: 10px 50px;
          box-shadow: 0 0 2px #efefef;
          background-color: #f5f7fa;
          .info-label {
            padding: 10px 20px;
            line-height: 36px;
            height: 36px;
            font-weight: 600;
            border-bottom: 1px solid #f0f0f2;
          }
          .info-row {
            padding: 0 20px;
            display: flex;
            align-items: center;
            line-height: 45px;
            height: 45px;
            &:hover {
              .row-action {
                opacity: 1;
              }
            }
            .edit-box {
              display: flex;
              align-items: center;
              margin-left: 20px;
              ::v-deep(.el-input__wrapper) {
                border-bottom: 1px solid #c0c4cc;
                border-radius: 0;
                background-color: #f5f7fa;
                margin-right: 20px;
                box-shadow: 0 0 0 0;
              }
              
            }
            .content-box {
              display: flex;
              align-items: center;
            }
            .row-label {
              display: flex;
              justify-content: space-between;
              width: 70px;
              font-size: 14px;
              color: #555666;
            }
            .row-text {
              width: 200px;
              margin-left: 20px;
              font-size: 15px;
            }
            .row-action {
              opacity: 0;
            }
          }
          .password-form {
            width: 500px;
            margin: 20px auto;
            padding-bottom: 50px;
            .modify-password-aciton {
              text-align: right;
              margin-top: 10px;
              .confirm-btn {
                height: 40px;
                width: 180px;
              }
            }
            
          }
        }
      }
    }
    .avatar-dialog{
      display: flex;
      align-items: center;
      justify-content: center;
      .blank-box {
        width: 40px;
      }
      .avatar-uploader {
        ::v-deep(.el-upload) {
          border: 1px dashed var(--el-border-color);
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: var(--el-transition-duration-fast);
        }
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 360px;
        height: 158px;
        text-align: center;
      }
      
    }
  }
</style>